import urllib
import urllib2
import sys
import zipfile
import os.path
import os
import optparse
import time
from os import system, environ

jom = "http://releases.qt-project.org/jom/jom.zip"
qt_4 = "http://download.qt-project.org/official_releases/qt/4.8/4.8.5/qt-everywhere-opensource-src-4.8.5.zip"
qt_5 = "http://download.qt-project.org/official_releases/qt/5.2/5.2.1/single/qt-everywhere-opensource-src-5.2.1.zip"
qt_final_folder = "C:/Qtsource/"
qt_5_version = '5.2.1'
qt_4_version = '4.8.5'

jom_folder = qt_final_folder + "jom"
core = '2'
optionqt = "-debug-and-release -opensource -nomake examples -nomake tests -confirm-license "
#if you use openssl, change this 2 path
openssl_include = "C:/OpenSSL-Win32/include"
openssl_lib = "C:/OpenSSL-Win32/lib"

def mymakedir(dir):
	if not os.path.exists(dir):
		os.makedirs(dir)

def mycheckfile(file):
  if os.path.isfile(file):
    return True
  else:
    return False

def dlProgress(count, blockSize, totalSize):
      percent = int(count*blockSize*100/totalSize)
      sys.stdout.write("\r" + "%d%%" % percent)
      sys.stdout.flush()

def fileFromUrl(url):
	return url.split('/')[-1]

def createAndWriteFile(filename, content):
  tmpFile = open(filename, 'wb+')
  tmpFile.write(content)
  tmpFile.close() 

def downLoadFile(url):
	urllib.urlretrieve(url, fileFromUrl(url), reporthook=dlProgress)
	print "\n"

parser = optparse.OptionParser()
parser.add_option('-j', '--jom', help='Use jom and not nmake', dest='jom', action='store_true')
parser.add_option('-c', '--compiler', default='2012', help='Select Visual Studio version. Option:2012, 2010 default:[%default]', dest='compiler', action='store')
parser.add_option('-l', '--link', default='shared', help='Compile Qt in [static] or [shared] mode. Default:[%default]', dest='link', action='store')
parser.add_option('-o', '--openssl', help='Compile Qt with openssl support', dest='openssl', action='store_true')
parser.add_option('-f', '--force', help='Force the script to bypass all the code up to the rename of qt folder', dest='force', action='store_true')
parser.add_option('-v', '--version', default='5', help='Select the version of Qt: [4] or [5]. Default:[%default]', dest='version', action='store')
parser.add_option('--noconfigure', help='Bypass the configure operation', dest='configure', action='store_true')
parser.add_option('--nodebug', help='Disable wainting in configure part and build part', dest='debug', action='store_true')
parser.add_option('--noclean', help='Disable jom clean at the end of building', dest='clean', action='store_true')
parser.add_option('--delete', help='Delete downloaded files after the unzip', dest='delete', action='store_true')

(opts, args) = parser.parse_args()

current_version = ''
current_url = ''
if opts.version is '5':
  current_version = qt_5_version
  current_url = qt_5
elif opts.version is '4':
  current_version = qt_4_version
  current_url = qt_4
else:
  print "Bad argument: " + opts.version + "\n"
  parser.print_help()
  exit(-1)

qt_source_folder = qt_final_folder + current_version
qt_source_folder_tmp = qt_source_folder + "/source"
qt_exctractfolder = 'qt-everywhere-opensource-src-' + current_version

if opts.compiler is "2012":
  optionqt = optionqt + "-platform win32-msvc2012 "
elif opts.compiler is "2010":
  optionqt = optionqt + "-platform win32-msvc2010 "
else:
  print "Bad argument: " + opts.compiler + "\n"
  parser.print_help()
  exit(-1)

if opts.link is "shared":
  optionqt = optionqt + "-shared "
elif opts.link is "static":
  optionqt = optionqt + "-static "
else:
  print "Bad argument: " + opts.link + "\n"
  parser.print_help()
  exit(-1)

if opts.openssl is True:
  optionqt = optionqt + "-openssl -I " + openssl_include + " -L " + openssl_lib + " "

optionqt = optionqt + ' -prefix "' + qt_source_folder + '" '

if opts.force is None:
  mymakedir(qt_final_folder)
  mymakedir(qt_source_folder)

  if opts.jom is True:
    print "==> Downloading jom"
    if mycheckfile(fileFromUrl(jom)) is False:
      downLoadFile(jom)
    optionqt = optionqt + '-make-tool jom '
  else:
    optionqt = optionqt + '-mp '

  print "==> Downloading Qt " + current_version
  if mycheckfile(fileFromUrl(current_url)) is False:
    downLoadFile(current_url)

  if opts.jom is True:
    print "==> Unzip jam\n"
    mymakedir(jom_folder)
    zipp = zipfile.ZipFile(fileFromUrl(jom))
    zipp.extractall(jom_folder)
    if opts.delete is True:
      os.remove(fileFromUrl(jom))

  print "==> Unzip qt source\n"
  zipp = zipfile.ZipFile(fileFromUrl(current_url))
  zipp.extractall(qt_final_folder)
  if opts.delete is True:
    os.remove(fileFromUrl(current_url))
os.rename(qt_final_folder + qt_exctractfolder, qt_source_folder_tmp)

os.chdir(qt_source_folder_tmp)
if opts.configure is None:
  print "\n============== Configure ==============\n"
  if opts.debug is None:
    time.sleep(3)
    print "\n===> Start\n"
    time.sleep(1)
  os.system('configure ' + optionqt)

print "\n============== Build ==============\n"
if opts.jom is True:
  if opts.debug is None:
    time.sleep(5)
    print "\n===> Start\n"
    time.sleep(1)  
  os.system('..\\..\\jom\\jom.exe -j' + core )
  if opts.clean is None:
    print "\n============== Clean ==============\n"
    if opts.debug is None:
      time.sleep(5)
      print "\n===> Start\n"
      time.sleep(1)
    os.system('..\\..\\jom\\jom.exe clean')
else:
  os.system('nmake')